import { existplayer,Read_player,Write_player,Add_player,__PATH,get_player_img,Write_json,Read_json
  ,alluser,getGuojiaIndex,getGuojia } from "../game/sanguo.js";
import data from '../../model/sanguoData.js'
import fs from 'fs';
import Show from '../../model/show.js';
import puppeteer from '../../../../lib/puppeteer/puppeteer.js';
export class Start extends plugin {
    constructor() {
      super({
        /** 功能名称 */
        name: '三国|用户模块',
        /** 功能描述 */
        dsc: '基础模块',
        event: 'message',
        /** 优先级，数字越小等级越高 */
        priority: 600,
        rule: [
          {
            reg: /^(#|\/)踏入三国$/,
            fnc: 'Create_player',
          },
          {
            reg: /^(#|\/)进入三国$/,
            fnc: 'Create_player2',
          },
          {
            reg: /^(#|\/)改名.*$/,
            fnc: 'gai',
          },
          {
            reg: /^(#|\/)改性.*$/,
            fnc: 'gaix',
          },
          {
            reg: /^(#|\/)选择国家.*$/,
            fnc: 'chose',
          },
          {
            reg: /^(#|\/)个人信息$/,
            fnc: 'Show_player',
          },
          {
            reg: /^(#|\/)查看国家信息$/,
            fnc: 'check',
          },
          {
            reg: /^(#|\/)查看队伍.*$/,
            fnc: 'check2',
          },
          {
            reg: /^(#|\/)查看条约.*$/,
            fnc: 'check3',
          },
        ]
      });
    }
    async gaix(e){
      if (!e.isGroup) return;
      const usr_qq = e.user_id;
      if (!await existplayer(1,usr_qq)) return;
      let weizhi ;
      if(e.msg.includes("/")) weizhi = e.msg.replace("/改性", '');
      if(e.msg.includes("#"))weizhi = e.msg.replace("#改性", '');
      const player =await Read_player(1,usr_qq)
      player.sex = weizhi
      await Write_player(1,usr_qq, player);
      return e.reply(`已选择${weizhi}`)
    }
    async chose(e){
      if (!e.isGroup) return;
      const usr_qq = e.user_id;
      if (!await existplayer(1,usr_qq)) return;
      let weizhi ;
      if(e.msg.includes("/"))weizhi = e.msg.replace("/选择国家", '');
      if(e.msg.includes("#"))weizhi = e.msg.replace("#选择国家", '');
      const player =await Read_player(1,usr_qq)
      if(player.国家 !="无") return e.reply(`你已有国家`)
      if(weizhi !== "蜀汉"&&weizhi !=="曹魏"&&weizhi !== "东吴")return e.reply(`没有${weizhi}这个国家`)
      player.国家 = weizhi
      await Write_player(1,usr_qq, player);
      return e.reply(`已选择${weizhi}`)
    }
    async gai(e){
      if (!e.isGroup) return;
      const usr_qq = e.user_id;
      if (!await existplayer(1,usr_qq)) return;
      let weizhi ;
      if(e.msg.includes("/")) weizhi = e.msg.replace("/改名", '');
      if(e.msg.includes("#")) weizhi = e.msg.replace("#改名", '');
      const player =await Read_player(1,usr_qq)
      if (player.金钱 < 500) return e.reply(`金钱不够，还需要${500 - player.金钱}`)
      player.名号 = weizhi
      await Write_player(1,usr_qq, player);
      return e.reply(`已成功改名`)
    }
    async Create_player2(e) {
      if (!e.isGroup) return;
      const usr_qq = e.user_id;
      if (usr_qq == 80000000) return;
      if (await existplayer(1,usr_qq)) return this.Show_player;
      const n = fs.readdirSync(__PATH.player_path).length + 1;
      let new_player = {
        id: e.user_id,
        sex: 0, //性别
        名号: `路人甲${n}号`,
        宣言: '这个人很懒还没有写',
        国家:`无`,
        金钱: 10500,
        当前血量: 8000,
        血量上限: 8000,
        暴击率:0.1,
        暴击伤害:0.1,
        攻击加成: 1000,
        防御加成: 1000,
        生命加成: 1000,
      }; 
      let new_equipment = {
        武器: data.equipment_list.find(item => item.name == '烂铁匕首'),
        护具: data.equipment_list.find(item => item.name == '破铜护具'),
        法宝: data.equipment_list.find(item => item.name == '廉价炮仗'),
      }; 
      let new_bag = {
        等级: 1,
        金钱上限: 5000,
      };
      await Write_player(2,usr_qq, new_equipment);
      await Write_player(1,usr_qq, new_player);
      await Write_player(3,usr_qq, new_bag);
      await Add_player(1,usr_qq, 999999);
      return e.reply(`已成功进入三国，请用别的指令设置国家和名字以防出bug`)
    }
    async Create_player(e) {
        //不开放私聊功能
        if (!e.isGroup) return;
        let usr_qq = e.user_id;
        //判断是否为匿名创建存档
        if (usr_qq == 80000000) return;
        //有无存档
        if ( await existplayer(1,usr_qq)) return this.Show_player;
        //初始化玩家信息
        let File_msg = fs.readdirSync(__PATH.player_path);
        let n = File_msg.length + 1;
        let new_player = {
          id: e.user_id,
          sex: 0, //性别
          名号: `路人甲${n}号`,
          宣言: '这个人很懒还没有写',
          国家:`无`,
          金钱: 10000,
          当前血量: 8000,
          血量上限: 8000,
          暴击率:0.1,
          暴击伤害:0.1,
          攻击加成: 1000,
          防御加成: 1000,
          生命加成: 1000,
        
        };
        //初始化装备
        let new_equipment = {
          武器: data.equipment_list.find(item => item.name == '烂铁匕首'),
          护具: data.equipment_list.find(item => item.name == '破铜护具'),
          法宝: data.equipment_list.find(item => item.name == '廉价炮仗'),
        };
        //初始化纳戒
        let new_bag = {
          等级: 1,
          金钱上限: 5000,
        };
        await Write_player(2,usr_qq, new_equipment);
        await Write_player(1,usr_qq, new_player);
        await Write_player(3,usr_qq, new_bag);
        await Add_player(1,usr_qq, 999999);
        this.setContext('player_name');
        await e.reply('请输入你的游戏名(名字最多7个字)', false, {
          at: true,})
        return;
      }
      async player_name(e) {
        if (!e.isGroup)
            return;
        const newMsg = this.e.message;
        if (newMsg[0].type != 'text') {
            this.setContext('player_name');
            return await this.reply('请发送文本,请重新输入:');
        }
        const player_name = newMsg[0].text;
        if (player_name.length > 7) {
            this.setContext('player_name');
            return await this.reply('名号最多只能设置7个字符,请重新输入:');
        }
  
        let usr_qq = e.user_id;
        let player = await Read_player(1,usr_qq);
        player.名号 = player_name;
        await Write_player(1,usr_qq, player);
        this.finish('player_name');
        await redis.set('wanjiexiuxian:player:' + usr_qq + ':start_name', player_name);
        await e.reply('请输入你的性别男或女', false, {
            at: true,
        });
        this.setContext('player_sex');
        return;
    }
    async player_sex(e) {
        if (!e.isGroup)
            return;
        const sex2 = new RegExp(/男|女/);
        const newMsg2 = this.e.msg;
        const sex3 = sex2.exec(newMsg2);
        if (sex3 == undefined || sex3 == null) {
            this.setContext('player_sex');
            await e.reply('请输入你的性别男或女', false, {
                at: true,
            });
            return;
        }
        const usr_qq = e.user_id;
        let player = await Read_player(1,usr_qq);
        if (sex3[0] === '男') player.sex = '男';
        else if (sex3[0] === '女') player.sex = '女';
        await Write_player(1,usr_qq, player);
        this.finish('player_sex');
        await e.reply('请选择你的加入的国家【曹魏】【蜀汉】【东吴】', false, {
            at: true,
        });
        this.setContext('guojia');
        return;
    }
    async guojia(e) {
        if (!e.isGroup) return;
        const usr_qq = e.user_id;
        let player = await Read_player(1,usr_qq);
        var reg = new RegExp(/曹魏|蜀汉|东吴/);
        let new_msg = this.e.msg, difficulty = reg.exec(new_msg);
        if (difficulty == undefined || difficulty == null) {
          await e.reply('请选择你的种族【曹魏】【蜀汉】【东吴】', false, {
            at: true, });
            this.setContext('guojia'); 
          return;
        }
        /** 结束上下文 */
        this.finish('guojia');
        let zhongzu;
        switch (difficulty[0]) {
          case '曹魏': zhongzu ='曹魏'; break;
          case '蜀汉': zhongzu ='蜀汉'; break;
          case '东吴': zhongzu ='东吴'; break;
        }
        player.国家 = zhongzu;
        let guojia = await getGuojia(player.国家)
        guojia.player.push(usr_qq)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        await Write_player(1,usr_qq, player);
        await Add_player(1,usr_qq, 999999);
        e.reply([segment.at(usr_qq), `你出生在${player.国家}"，\n可以在【#个人信息】中查看`]);
        this.Show_player(e)
        return;
      }
      async Show_player(e){
        //不开放私聊功能
        let usr_qq = e.user_id;
        //有无存档
        if (!await existplayer(1,usr_qq)) return;
        return e.reply(await get_player_img(e,usr_qq));
      }
      async check(e){
        if (!e.isGroup) return;
        const usr_qq = e.user_id;
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let allusr_qq = await alluser();
        let playerPromises = allusr_qq.map(qq => Read_player(1, qq));
        let playerResults = await Promise.all(playerPromises);
        guojia.经济 = 0;
        for (let i = 0; i < allusr_qq.length; i++) {
          let qq = allusr_qq[i];
          let allplayer = playerResults[i];
          if (allplayer.国家 === player.国家) {
            guojia.经济 += allplayer.金钱;
            await Write_json(await getGuojiaIndex(player.国家), guojia);
          }
        }
        // let type=["剑兵","骑兵","长矛兵","弓兵"]
        // let type2=["重骑兵","骑射兵","火弓兵","弩弓兵","神射手","重剑兵","轻剑兵", "神剑兵","重矛兵","神矛兵"]
        // let pu =[]
        // let te =[]
        //   const 普通兵种结果= Object.entries(guojia.普通兵种)
        //  .filter(([兵种名称, 数量]) => 数量 !== 0)
        //  .map(([兵种名称, 数量]) => `${兵种名称} x ${数量}`) .join('\n');;
        //   // 格式化普通兵种信息
        //     // const 普通兵种结果 = Object.entries(guojia.普通兵种)
        //     // .filter(([兵种, 数量]) => 数量 > 0)
        //     // .map(([兵种, 数量]) => `${兵种}: ${数量}`)
        //     // .join('\n');

        //     // 格式化特殊兵种信息
        //     const 特殊兵种结果 = Object.entries(guojia.特殊兵种)
        //     .filter(([兵种名称, 数量]) => 数量 > 0)
        //     .map(([兵种名称, 数量]) => `${兵种名称} x ${数量}`) .join('\n');;
        //     console.log(特殊兵种结果);
        //     console.log(普通兵种结果);
        //     // 格式化武将信息
        //     const 武将结果 = guojia.武将
        //     .filter(武将 => 武将.数量 !== 0)
        //     .map(武将 => `${武将.name} x ${武将.数量}`)
        //     .join('\n');

        //     // 构建国家信息文本
        //     const 国家信息文本 = `
        //     国家名字为: ${player.国家}
        //     国家玩家人数为: ${guojia.player.length}
        //     国家人口为: ${guojia.人口}
        //     国家经济为: ${guojia.经济}
        //     科技等级为: ${guojia.科技}
        //     科技经验为: ${guojia.科技exp}
        //     国家的兵力为: ${guojia.兵力}
        //     国家的赋税: ${guojia.赋税}
        //     武将:
        //     ${武将结果}
        //     普通兵种:
        //     ${普通兵种结果}
        //     特殊兵种:
        //     ${特殊兵种结果}`;

        //     // 使用 e.reply 发送结果
        //     // e.reply(`国家名字为:${player.国家}\n国家玩家人数为:${guojia.player.length}\n国家人口为:${guojia.人口}\n国家经济为:${guojia.经济}\n科技等级为${guojia.科技}
        //     // \n科技经验为${guojia.科技exp}\n国家的兵力为${guojia.兵力}\n国家的赋税${guojia.赋税}\n武将:\n${result}\n普通兵种:\n${普通兵种结果}\n\n特殊兵种:\n${特殊兵种结果}`);
  
          
            
        //     e.reply(`国家信息：\n${国家信息文本}`);
        player = guojia.player.length
        let get_data={guojia: guojia,
          player:player,
          people:Math.floor(guojia.人口),
        
        }
        const data1 = await new Show().get_guojia(get_data);
        let img = await puppeteer.screenshot('guojia', {
            ...data1,
        });
        return e.reply(img);
      }
      // async getGuojia(e, weizhi) {
      //   let get_data={guojia: weizhi,}
      //   const data1 = await new Show().get_guojia(get_data);
      //   let img = await puppeteer.screenshot('guojia', {
      //       ...data1,
      //   });
      //     e.reply(img)
      //   }
     async check2(e){
        if (!e.isGroup) return;
        const usr_qq = e.user_id;
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let name = e.msg.includes('/') ? e.msg.replace('/查看队伍', '') : e.msg.includes('#') ? e.msg.replace('#查看队伍', '') : ''.trim();
        let x = guojia.队伍.find(item => parseInt(item.编号) === parseInt(name));
        if(!x)return e.reply(`没有这个队伍`)
        let get_data={duiwu: x}
        const data1 = await new Show().get_guojiaduiwu(get_data);
        let img = await puppeteer.screenshot('guojia', {
            ...data1,
        });
        return e.reply(img);
     }
     async check3(e){
      if (!e.isGroup) return;
        const usr_qq = e.user_id;
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let name = e.msg.includes('/') ? e.msg.replace('/查看条约', '') : e.msg.includes('#') ? e.msg.replace('#查看条约', '') : ''.trim();
        let x = guojia.条约.find(item => toString(item.name) === toString(name));
        if(!x)return e.reply(`没有这个条约`)
        let get_data={duiwu: x}
        const data1 = await new Show().get_guojiatiaoyue(get_data);
        let img = await puppeteer.screenshot('guojia', {
            ...data1,
        });
        return e.reply(img);
     }
}